package com.ldj.tim.server.server;

import com.ldj.tim.common.constant.Constants;
import com.ldj.tim.common.constant.MqConstants;
import com.ldj.tim.common.dto.P2PInfoDTO;
import com.ldj.tim.common.pojo.P2GroupInfo;
import com.ldj.tim.common.pojo.P2PInfo;
import com.ldj.tim.common.protocol.TIMReqMsg;
import com.ldj.tim.server.util.OfflineMessageUtil;
import com.ldj.tim.server.api.vo.req.SendMsgReqVO;
import com.ldj.tim.server.init.TIMServerInitializer;
import com.ldj.tim.server.util.SessionSocketHolder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;
import java.util.UUID;

/**
 * @since JDK 1.8
 */
@Component
public class TIMServer {

    private final static Logger LOGGER = LoggerFactory.getLogger(TIMServer.class);

    private EventLoopGroup boss = new NioEventLoopGroup();
    private EventLoopGroup work = new NioEventLoopGroup();

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OfflineMessageUtil offlineMessageUtil;

    @Value("${tim.server.port}")
    private int nettyPort;


    /**
     * 启动 tim server
     *
     * @return
     * @throws InterruptedException
     */
    @PostConstruct
    public void start() throws InterruptedException {

        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(boss, work)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(nettyPort))
                //保持长连接
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new TIMServerInitializer());

        ChannelFuture future = bootstrap.bind().sync();
        if (future.isSuccess()) {
            LOGGER.info("Start tim server success!!!");
        }
    }


    /**
     * 销毁
     */
    @PreDestroy
    public void destroy() {
        boss.shutdownGracefully().syncUninterruptibly();
        work.shutdownGracefully().syncUninterruptibly();
        LOGGER.info("Close tim server success!!!");
    }


    /**
     * Push msg to client.
     *
     * @param sendMsgReqVO 消息
     */
    public void sendMsg(SendMsgReqVO sendMsgReqVO) {
        Channel socketChannel = SessionSocketHolder.get(sendMsgReqVO.getUserId());
        String msg = sendMsgReqVO.getMsg();
        boolean p2pFlag = msg.contains("-");
        String mid = UUID.randomUUID().toString();
        //一根是单聊
        if (p2pFlag) {
            Long senderId = Long.parseLong(msg.split("-")[0]);
            P2PInfo p2PInfo = new P2PInfo();
            p2PInfo.setMsgId(mid);
            p2PInfo.setMessage(sendMsgReqVO.getMsg().split("-")[1]);
            p2PInfo.setTimestamp(System.currentTimeMillis());
            p2PInfo.setOwnerUid(senderId);
            p2PInfo.setOtherUid(sendMsgReqVO.getUserId());
            p2PInfo.setBoxType(Constants.MsgBoxType.SHIPPING_BOX);
            //利用mq流量削峰，消费者插入数据
            rabbitTemplate.convertAndSend(MqConstants.EXCHANGE_NAME, MqConstants.ROUTING_KEY, p2PInfo);
            if (null == socketChannel) {
                LOGGER.error("client {} offline!", sendMsgReqVO.getUserId());
                //redis存储最新十条离线消息
                offlineMessageUtil.addMessageToQueue(sendMsgReqVO.getUserId(), String.valueOf(p2PInfo.getOwnerUid()), p2PInfo);
                return;
            }
        } else {
            //todo 待定
            Long senderId = Long.parseLong(msg.split("--")[0]);
            P2GroupInfo p2GroupInfo = new P2GroupInfo();
            p2GroupInfo.setMsgId(mid);
            p2GroupInfo.setTimestamp(System.currentTimeMillis());
            p2GroupInfo.setReceiverId(senderId);
            //利用mq流量削峰，消费者插入数据
            rabbitTemplate.convertAndSend(MqConstants.EXCHANGE_NAME, MqConstants.ROUTING_KEY, p2GroupInfo);
            if (null == socketChannel) {
                LOGGER.error("client {} offline!", sendMsgReqVO.getUserId());
                //redis存储最新十条离线消息
//                offlineMessageUtil.addMessageToQueue(sendMsgReqVO.getUserId(), String.valueOf(p2GroupInfo.getGroupId()), p2GroupInfo);
                return;
            }
        }
        TIMReqMsg protocol = new TIMReqMsg(sendMsgReqVO.getUserId(), sendMsgReqVO.getMsg(), Constants.CommandType.MSG);
        ChannelFuture future = socketChannel.writeAndFlush(protocol);
        future.addListener((ChannelFutureListener) channelFuture ->
                LOGGER.info("server push msg:[{}]", sendMsgReqVO));
    }
}
